package webmarket.common;

import java.util.HashMap;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

/**
 * 
 * Helper class for JSONmapping
 *
 */
public class JSONMapper {
	private Map<String, Object> map;

	public JSONMapper() {
		this(new HashMap<String, Object>());
	}

	public JSONMapper(Map<String, Object> map) {
		this.map = map;
	}

	public JSONMapper(String json) {
		ReadJSON(json);
	}

	public void ReadJSON(String json) { 
		ObjectMapper mapper = new ObjectMapper();
		try {
			// convert JSON string to Map
			map = mapper.readValue(json, new TypeReference<HashMap<String, String>>() {});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String WriteJSON() {
		return this.toString();
	}

	@Override
	public String toString() {
		String json = "";
		try {
			ObjectMapper mapper = new ObjectMapper();
			// convert map to JSON string
			json = mapper.writeValueAsString(map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json;
	}

	public void put(String parameter, Object value) {
		map.put(parameter, value);
	}
	
	public void put(ValidationObject value){
		put(value.getName(), value);
	}

	public Object get(String parameter) {
		return map.get(parameter);
	}

	public Map<String, Object> get() {
		return this.map;
	}
}
